package oauth

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

// generateState 生成包含原始URL的state
func generateState(r *http.Request) string {
	// 生成随机字符串
	b := make([]byte, 16)
	rand.Read(b)
	randomStr := base64.URLEncoding.EncodeToString(b)
	
	// 编码原始请求URL
	originalURL := fmt.Sprintf("%s://%s%s", r.URL.Scheme, r.Host, r.URL.RequestURI())
	return fmt.Sprintf("%s_%s", randomStr, url.QueryEscape(originalURL))
}

// parseState 从state中解析原始URL
func parseState(state string) (string, error) {
	parts := strings.Split(state, "_")
	if len(parts) != 2 {
		return "", fmt.Errorf("invalid state format")
	}
	return url.QueryUnescape(parts[1])
} 